import { ADD_COUNTER, ADD_TO_CART } from './mutations-types'

export default {
  addCart({ state, commit }, payload) {
    // 方法1：for
    // let oldProduct = null
    // for (let item of state.cartList) {
    //   if (item.id === payload.iid) {
    //     oldProduct = item
    //   }
    // }
    // 方法2：arr.find()
    // 1.查找之前數組中是否有该商品
    return new Promise((resolve, reject) => {
      let oldProduct = state.cartList.find(item => item.iid === payload.iid)
      // 2、判断oldProduct
      if (oldProduct) {
        // oldProduct.count += 1
        commit(ADD_COUNTER, oldProduct)
        resolve('当前的商品数量+1')
      } else {
        payload.count = 1
        commit(ADD_TO_CART, payload)
        resolve('添加新的商品')
      }
    })
  }
}
